<?php
/**
 * Route Url Action Helper
 * This action helper generates a URL based on a route name and parameters. It
 * is an exact copy of the RouteUrl view helper.
 * It requires the use of a Zend_View object in order to use its "Url" helper.
 * 
 * @package 	Visi
 * @subpackage 	Action Helpers
 * @author 		Luke Visinoni <luke.visinoni@gmail.com>
 * @copyright 	(c) 2010 Luke Visinoni <luke.visinoni@gmail.com>
 * @todo 		This is exact duplicate code of the RouteUrl view helper. Find a
 * 				way to not duplicate code
 * @todo 		There are places in the controllers where I've either assembled
 * 				a route directly or used the view helper. Like in the app
 * 				controller probably. Replace that code with this
 * @todo 		I am thinking it might be a good idea to just proxy the
 * 				"RouteUrl" view helper here since I'm using a view helper anyway
 */
class Visi_Controller_Action_Helper_RouteUrl extends Zend_Controller_Action_Helper_Abstract {

    protected $_view;
    
    public function init() {
    
        if (is_null($this->_view)) {
            $this->_view = new Zend_View;
        }
        return parent::init();
    
    }
    
    public function setView(Zend_View_Abstract $view) {
    
        $this->_view = $view;
    
    }
    
    public function direct($name = null, $urlOptions = array(), $getParams = array(), $reset = false, $encode = true) {
    
        $front = Zend_Controller_Front::getInstance();
        $routes = array_keys($front->getRouter()->getRoutes());
		if (is_null($urlOptions)) $urlOptions = array();
    	// if $name isn't an existing route, assume they meant to call a url
        if (!in_array($name, $routes)) {
            $url = rtrim($front->getBaseUrl(), '/') . '/';
            $url .= ltrim($name, "/");
        } else {
            if (is_null($name)) $name = "default";
            $url = $this->_view->url($urlOptions, $name, $reset, $encode);
        }
        // put together the GET parameters
        $queryString = "";
        $queryPairs = array();
        foreach ($getParams as $name => $value) {
                $queryPairs[] = "$name=$value";
        }
        if (!empty($queryPairs)) {
                $queryString = "?" . implode("&", $queryPairs);
        }
        return $url . $queryString;
    
    }

}